package cn.cagurzhan.service;

import cn.cagurzhan.common.constant.HttpStatus;
import cn.cagurzhan.domain.R;
import cn.cagurzhan.domain.dto.LoginDto;
import cn.cagurzhan.domain.entity.User;
import cn.cagurzhan.mapper.UserMapper;
import cn.cagurzhan.utils.AppJwtUtil;
import cn.cagurzhan.utils.ServletUtils;
import cn.cagurzhan.utils.spring.SpringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author AjaxZhan
 */
@Service
@RequiredArgsConstructor
public class LoginService {

    private final UserMapper userMapper;

    private final CacheService cacheService;

    /**
     * 用户登录
     * @param loginDto 账户 密码
     * @return token
     */
    public R<Map<String,Object>> login(LoginDto loginDto){
        // 查询用户
        if(StringUtils.isNotBlank(loginDto.getUsername()) && StringUtils.isNotBlank(loginDto.getPassword())){
            User user = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, loginDto.getUsername()));
            // 用户不存在
            if(user == null){
                return R.fail(HttpStatus.UNAUTHORIZED,"校验失败，用户信息不存在");
            }
            // 检验密码
            String encodePwd = user.getSalt() + loginDto.getPassword();
            String md5DecodePwd = DigestUtils.md5DigestAsHex(encodePwd.getBytes());
            if(!md5DecodePwd.equals(user.getPassword())){
                return R.fail(HttpStatus.UNAUTHORIZED,"校验失败，密码错误");
            }
            // 校验成功，生成jwt
            String token = AppJwtUtil.getToken(user.getUserId().longValue());
            Map<String,Object> ajax = new HashMap<>();
            ajax.put("token",token);
            ajax.put("user-id",user.getUserId());
            return R.ok(ajax);
        }
        return R.fail(HttpStatus.UNAUTHORIZED,"请提供正确的参数");
    }
}
